package common

import (
	"context"
	"fmt"
	"github.com/go-redis/redis/v8"
	"github.com/pkg/errors"
	"log"
)

var Rdb *redis.Client

func InitDB() error {
	conf, err := GetConfig()
	if err != nil {
		return err
	}
	Rdb = redis.NewClient(&redis.Options{
		Addr:     fmt.Sprintf("%v:%v", conf.Host, conf.Port),
		Password: conf.Password,
		DB:       conf.Db,
	})
	ctx := context.Background()
	err = Rdb.Ping(ctx).Err()
	if err != nil {
		return errors.Wrap(err,"ERR: fail to connect redis")
	}
	fmt.Println("连接成功")
	return nil
}

func GetRdb() *redis.Client {
	return Rdb
}

func init() {
	err := InitDB()
	if err != nil {
		log.Fatalf("add error info: %+v", err)
	}
}